package ysq.xyg.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import ysq.xyg.base.controller.BaseController;
import ysq.xyg.web.model.po.WebAccount;
import ysq.xyg.wxapi.api.WxMemoryCacheClient;
import ysq.xyg.wxapi.model.base.MsgRequest;
import ysq.xyg.wxapi.service.WxService;
import ysq.xyg.wxapi.util.MsgXmlUtil;
import ysq.xyg.wxapi.util.SignUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信端controller层
 *
 * @author shengQiang yu
 * @date 2019-4-26 11:34:01
 */
@Controller
@RequestMapping("/weiXin")
public class WeXinController extends BaseController {
    private static final Logger log= LoggerFactory.getLogger(WeXinController.class);
    @Resource
    private WxService wxService;

    /**
     * GET请求：进行URL、Tocken 认证；
     * 1. 将token、timestamp、nonce三个参数进行字典序排序
     * 2. 将三个参数字符串拼接成一个字符串进行sha1加密
     * 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     */
    @RequestMapping(value = "/api",  method = RequestMethod.GET)
    public @ResponseBody
    String doGet(HttpServletRequest request) {
        //如果是多账号，根据url中的account参数获取对应的MpAccount处理即可
        WebAccount wxAccountInfo = WxMemoryCacheClient.getSingleWxAccountInfo();//获取缓存中的唯一账号
        if(wxAccountInfo != null){
            String token = wxAccountInfo.getToken();//获取token，进行验证；
            System.out.print(token);
            String signature = request.getParameter("signature");// 微信加密签名
            String timestamp = request.getParameter("timestamp");// 时间戳
            String nonce = request.getParameter("nonce");// 随机数
            String echostr = request.getParameter("echostr");// 随机字符串
            // 校验成功返回  echostr，成功成为开发者；否则返回error，接入失败
            if (SignUtil.validSign(signature, token, timestamp, nonce)) {
                return echostr;
            }
        }
        return "error";
    }
    /**
     * POST 请求：进行消息处理；
     * */
    @RequestMapping(value = "/api", method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    public @ResponseBody String doPost(HttpServletRequest request,HttpServletResponse response) {
        //处理用户和微信公众账号交互消息
        WebAccount webAccount = WxMemoryCacheClient.getSingleWxAccountInfo();//获取缓存中的唯一账号
        try {
            MsgRequest msgRequest = MsgXmlUtil.parseXml(request);//获取发送的消息
            return wxService.wxManager(request,msgRequest,webAccount);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}
